import { Card, Button, Modal, Form, Input, Select, message, Space, Popconfirm, Row, Col, Typography, Tabs } from '@/utils/antd-imports';
import { PlusOutlined, EditOutlined, DeleteOutlined, ApartmentOutlined } from '@/utils/icons';
import { OrganizationChart } from '@ant-design/charts';
import React, { useState } from 'react';

const { Option } = Select;
const { Text, Title } = Typography;
const { TabPane } = Tabs;

// 模拟组织架构数据 - 转换为OrganizationChart格式
const generateOrgData = () => {
  return {
    id: '1',
    value: {
      title: '总公司',
      name: '凯泽利科技有限公司',
      type: 'company',
      level: 1,
      description: '公司总部'
    },
    children: [
      {
        id: '1-1',
        value: {
          title: '技术部',
          name: '技术部',
          type: 'department',
          level: 2,
          description: '负责技术研发'
        },
        children: [
          {
            id: '1-1-1',
            value: {
              title: '前端组',
              name: '前端开发组',
              type: 'team',
              level: 3,
              description: '负责前端开发'
            }
          },
          {
            id: '1-1-2',
            value: {
              title: '后端组',
              name: '后端开发组',
              type: 'team',
              level: 3,
              description: '负责后端开发'
            }
          },
          {
            id: '1-1-3',
            value: {
              title: '测试组',
              name: '测试组',
              type: 'team',
              level: 3,
              description: '负责软件测试'
            }
          }
        ]
      },
      {
        id: '1-2',
        value: {
          title: '市场部',
          name: '市场部',
          type: 'department',
          level: 2,
          description: '负责市场推广'
        },
        children: [
          {
            id: '1-2-1',
            value: {
              title: '销售组',
              name: '销售组',
              type: 'team',
              level: 3,
              description: '负责产品销售'
            }
          },
          {
            id: '1-2-2',
            value: {
              title: '推广组',
              name: '推广组',
              type: 'team',
              level: 3,
              description: '负责市场推广'
            }
          }
        ]
      },
      {
        id: '1-3',
        value: {
          title: '人事部',
          name: '人事部',
          type: 'department',
          level: 2,
          description: '负责人力资源管理'
        },
        children: [
          {
            id: '1-3-1',
            value: {
              title: '招聘组',
              name: '招聘组',
              type: 'team',
              level: 3,
              description: '负责人员招聘'
            }
          },
          {
            id: '1-3-2',
            value: {
              title: '培训组',
              name: '培训组',
              type: 'team',
              level: 3,
              description: '负责员工培训'
            }
          }
        ]
      },
      {
        id: '1-4',
        value: {
          title: '财务部',
          name: '财务部',
          type: 'department',
          level: 2,
          description: '负责财务管理'
        },
        children: [
          {
            id: '1-4-1',
            value: {
              title: '会计组',
              name: '会计组',
              type: 'team',
              level: 3,
              description: '负责会计核算'
            }
          },
          {
            id: '1-4-2',
            value: {
              title: '出纳组',
              name: '出纳组',
              type: 'team',
              level: 3,
              description: '负责资金管理'
            }
          }
        ]
      }
    ]
  };
};

const OrganizationStructure = () => {
  const [orgData, setOrgData] = useState(generateOrgData());
  const [modalVisible, setModalVisible] = useState(false);
  const [currentNode, setCurrentNode] = useState(null);
  const [form] = Form.useForm();
  const [activeTab, setActiveTab] = useState('chart');

  // 组织类型选项
  const orgTypeOptions = [
    { label: '公司', value: 'company' },
    { label: '部门', value: 'department' },
    { label: '科室/小组', value: 'team' }
  ];

  // 处理添加节点
  const handleAdd = (parentId = null) => {
    setCurrentNode({ parentId, type: 'add' });
    form.resetFields();
    setModalVisible(true);
  };

  // 处理编辑节点
  const handleEdit = (nodeData) => {
    setCurrentNode({ ...nodeData, type: 'edit' });
    form.setFieldsValue({
      title: nodeData.value.title,
      name: nodeData.value.name,
      type: nodeData.value.type,
      description: nodeData.value.description || ''
    });
    setModalVisible(true);
  };

  // 处理删除节点
  const handleDelete = (nodeData) => {
    const deleteNode = (data, id) => {
      if (data.id === id) {
        return null;
      }
      if (data.children) {
        data.children = data.children
          .map(child => deleteNode(child, id))
          .filter(child => child !== null);
      }
      return data;
    };
    
    const newData = deleteNode(orgData, nodeData.id);
    if (newData) {
      setOrgData(newData);
      message.success('删除成功');
    }
  };

  // 提交表单
  const handleSubmit = () => {
    form.validateFields().then(values => {
      const { title, name, type, description } = values;
      const newNode = {
        id: `${Date.now()}`,
        value: {
          title,
          name,
          type,
          description,
          level: currentNode.parentId ? 
            (findNodeById(orgData, currentNode.parentId)?.value.level + 1 || 2) : 1
        },
        children: []
      };

      if (currentNode.type === 'add') {
        if (currentNode.parentId) {
          // 添加子节点
          const addChildNode = (data, parentId, newNode) => {
            if (data.id === parentId) {
              return {
                ...data,
                children: [...(data.children || []), newNode]
              };
            }
            if (data.children) {
              return {
                ...data,
                children: data.children.map(child => addChildNode(child, parentId, newNode))
              };
            }
            return data;
          };
          setOrgData(addChildNode(orgData, currentNode.parentId, newNode));
        } else {
          // 添加根节点
          setOrgData([...orgData, newNode]);
        }
        message.success('添加成功');
      } else {
        // 编辑节点
        const updateNode = (data, id, updates) => {
          if (data.id === id) {
            return {
              ...data,
              value: { ...data.value, ...updates }
            };
          }
          if (data.children) {
            return {
              ...data,
              children: data.children.map(child => updateNode(child, id, updates))
            };
          }
          return data;
        };
        setOrgData(updateNode(orgData, currentNode.id, { title, name, type, description }));
        message.success('更新成功');
      }

      setModalVisible(false);
      form.resetFields();
    });
  };

  // 根据id查找节点
  const findNodeById = (node, id) => {
    if (node.id === id) return node;
    if (node.children) {
      for (const child of node.children) {
        const found = findNodeById(child, id);
        if (found) return found;
      }
    }
    return null;
  };

  // 组织图配置
  const orgConfig = {
    data: orgData,
    nodeCfg: {
      style: (node) => {
        const colors = {
          company: '#1890ff',
          department: '#52c41a',
          team: '#faad14'
        };
        return {
          fill: colors[node.value.type] || '#d9d9d9',
          stroke: '#fff',
          lineWidth: 2,
          radius: 8
        };
      },
      label: {
        style: (node) => ({
          fill: '#fff',
          fontSize: 12,
          fontWeight: 'bold'
        })
      }
    },
    edgeCfg: {
      style: {
        stroke: '#91d5ff',
        lineWidth: 2
      }
    },
    behaviors: ['drag-canvas', 'zoom-canvas', 'drag-node'],
    onReady: (graph) => {
      // 图表准备就绪
    },
    onNodeClick: (evt) => {
      const { item } = evt;
      const nodeData = item.getModel();
      setCurrentNode(nodeData);
    }
  };

  return (
    <div>
      <Card
        title={
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <ApartmentOutlined style={{ marginRight: 8 }} />
            组织架构管理
          </div>
        }
        extra={
          <Space>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={() => handleAdd()}
            >
              添加根节点
            </Button>
            {currentNode && (
              <Space>
                <Button 
                  icon={<EditOutlined />}
                  onClick={() => handleEdit(currentNode)}
                >
                  编辑
                </Button>
                <Popconfirm
                  title="确定要删除这个节点吗？"
                  onConfirm={() => handleDelete(currentNode)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button 
                    danger
                    icon={<DeleteOutlined />}
                  >
                    删除
                  </Button>
                </Popconfirm>
              </Space>
            )}
          </Space>
        }
      >
        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          style={{ marginBottom: 16 }}
        >
          <TabPane tab="组织图" key="chart" />
          <TabPane tab="树形结构" key="tree" />
        </Tabs>

        {activeTab === 'chart' ? (
          <div style={{ height: '600px', border: '1px solid #f0f0f0', borderRadius: '6px' }}>
            <OrganizationChart {...orgConfig} />
          </div>
        ) : (
          <div style={{ maxHeight: '600px', overflow: 'auto' }}>
            {renderTreeView(orgData)}
          </div>
        )}
      </Card>

      {/* 添加/编辑节点对话框 */}
      <Modal
        title={currentNode?.type === 'add' ? '添加节点' : '编辑节点'}
        visible={modalVisible}
        onOk={handleSubmit}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
        }}
        width={600}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label="节点标题"
            name="title"
            rules={[{ required: true, message: '请输入节点标题' }]}
          >
            <Input placeholder="请输入节点标题" />
          </Form.Item>
          
          <Form.Item
            label="节点名称"
            name="name"
            rules={[{ required: true, message: '请输入节点名称' }]}
          >
            <Input placeholder="请输入节点名称" />
          </Form.Item>
          
          <Form.Item
            label="组织类型"
            name="type"
            rules={[{ required: true, message: '请选择组织类型' }]}
          >
            <Select placeholder="请选择组织类型">
              {orgTypeOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            label="描述"
            name="description"
          >
            <Input.TextArea rows={3} placeholder="请输入描述信息" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );

  // 渲染树形视图
  function renderTreeView(node, level = 0) {
    const indent = level * 24;
    
    return (
      <div key={node.id} style={{ marginLeft: indent, marginBottom: 8 }}>
        <div 
          style={{ 
            padding: '8px 12px', 
            background: '#f5f5f5', 
            borderRadius: '4px',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            cursor: 'pointer'
          }}
          onClick={() => setCurrentNode(node)}
        >
          <div>
            <Text strong>{node.value.title}</Text>
            <Text type="secondary" style={{ marginLeft: 8 }}>
              ({orgTypeOptions.find(opt => opt.value === node.value.type)?.label})
            </Text>
            {node.value.description && (
              <div style={{ fontSize: 12, color: '#666', marginTop: 4 }}>
                {node.value.description}
              </div>
            )}
          </div>
          <Space>
            <Button 
              type="link" 
              size="small" 
              icon={<PlusOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                handleAdd(node.id);
              }}
            >
              添加
            </Button>
            <Button 
              type="link" 
              size="small" 
              icon={<EditOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                handleEdit(node);
              }}
            >
              编辑
            </Button>
            <Popconfirm
              title="确定要删除这个节点吗？"
              onConfirm={(e) => {
                e.stopPropagation();
                handleDelete(node);
              }}
              okText="确定"
              cancelText="取消"
            >
              <Button 
                type="link" 
                size="small" 
                danger
                icon={<DeleteOutlined />}
                onClick={(e) => e.stopPropagation()}
              >
                删除
              </Button>
            </Popconfirm>
          </Space>
        </div>
        {node.children && node.children.map(child => renderTreeView(child, level + 1))}
      </div>
    );
  }
};

export default OrganizationStructure;
